package com.ruoyi.web.service.Impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.pinyin.PinYinUtils;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.web.domain.MesUseDetail;
import com.ruoyi.web.domain.mes.MesMachinePaper;
import com.ruoyi.web.domain.mes.MesPaperTonFactor;
import com.ruoyi.web.mapper.MesConfigMapper;
import com.ruoyi.web.service.IMesCustomService;
import com.ruoyi.web.utils.EasyExcelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.ruoyi.web.mapper.MesPaperMapper;
import com.ruoyi.web.domain.mes.MesPaper;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * 纸张管理Service业务层处理
 *
 * @author levicash
 * @date 2024-01-09
 */

@Service
public class MesPaperService extends ServiceImpl<MesPaperMapper, MesPaper>  {
    private static final Logger log = LoggerFactory.getLogger(IMesCustomService.class);
    @Resource
    private MesPaperMapper mesPaperMapper;
    @Resource
    private MesConfigMapper configMapper;
    @Resource
    private MesPaperTonFactorService mesPaperTonFactorService;
    @Resource
    private SysDictDataMapper sysDictDataMapper;
    @Resource
    private HttpServletResponse response;

    /**
     * 查询纸张管理
     *
     * @param id 纸张管理主键
     * @return 纸张管理
     */

    public MesPaper selectMesPaperById(Long id) {
        MesPaper mesPaper = mesPaperMapper.selectMesPaperById(id);
        List<MesPaperTonFactor> list = mesPaperTonFactorService.list(new QueryWrapper<MesPaperTonFactor>()
                .lambda().eq(MesPaperTonFactor::getPaperId, id)
                .orderByAsc(MesPaperTonFactor::getId));
        mesPaper.setMesPaperTonFactors(list);
        return mesPaper;
    }


    public MesPaper selectMesPaperByCode(String code) {
        return mesPaperMapper.selectMesPaperByCode(code);
    }


    public List<MesPaper> selectMesPaperByIds(Long[] ids) {
        return mesPaperMapper.selectMesPaperByIds(ids);
    }

    /**
     * 查询纸张管理列表
     *
     * @param mesPaper 纸张管理
     * @return 纸张管理
     */

    public List<MesPaper> selectMesPaperList(MesPaper mesPaper) {
        return mesPaperMapper.selectMesPaperList(mesPaper);
    }

    //查询裁切组纸张
    public List<MesPaper> cuttingGrouplist(MesPaper mesPaper) {
        return mesPaperMapper.cuttingGrouplist(mesPaper);
    }

    /**
     * 新增纸张管理
     *
     * @param mesPaper 纸张管理
     * @return 结果
     */

    public int insertMesPaper(MesPaper mesPaper) {
        mesPaper.setCreateBy(SecurityUtils.getUsername());
        mesPaper.setCreateTime(DateUtils.getNowDate());
        // 生成纸张编号
        Map<String, Object> map = new HashMap<>();
        map.put("columnName", "code");
        map.put("tableName", "mes_paper");
        int maxNum = configMapper.getMaxId(map);
        String code = PinYinUtils.getCodeNormal(maxNum, "ZZGL");
        mesPaper.setCode(code);
        MesPaper paper = new MesPaper();
        paper.setName(mesPaper.getName());//纸张名称
        paper.setCustomId(mesPaper.getCustomId());//客户id
        paper.setPaperType(mesPaper.getPaperType());//纸型
        List<MesPaper> list = mesPaperMapper.selectMesPaperList(paper);
        if (list != null && list.size() > 0) {
            throw new ServiceException("已存在纸型纸张名称和客户相同数据！");
        }

        mesPaperMapper.insertMesPaper(mesPaper);
        Long id = mesPaperMapper.GetMaxId();

        if (mesPaper.getMesPaperTonFactors() != null && mesPaper.getMesPaperTonFactors().size() > 0) {
            for (MesPaperTonFactor tonfactor : mesPaper.getMesPaperTonFactors()) {
                tonfactor.setPaperId(id);
            }
            mesPaperTonFactorService.saveBatch(mesPaper.getMesPaperTonFactors());
        }

        return Math.toIntExact(id);
    }

    /**
     * 修改纸张管理
     *
     * @param mesPaper 纸张管理
     * @return 结果
     */

    public int updateMesPaper(MesPaper mesPaper) {
        mesPaper.setUpdateBy(SecurityUtils.getUsername());
        mesPaper.setUpdateTime(DateUtils.getNowDate());
        int count = mesPaperMapper.updateMesPaper(mesPaper);

        mesPaperTonFactorService.remove(new QueryWrapper<MesPaperTonFactor>().lambda()
                .eq(MesPaperTonFactor::getPaperId, mesPaper.getId()));
        if (mesPaper.getMesPaperTonFactors() != null && mesPaper.getMesPaperTonFactors().size() > 0) {
            for (MesPaperTonFactor tonfactor : mesPaper.getMesPaperTonFactors()) {
                tonfactor.setPaperId(mesPaper.getId());
            }
            mesPaperTonFactorService.saveBatch(mesPaper.getMesPaperTonFactors());
        }
        return count;
    }

    /**
     * 批量删除纸张管理
     *
     * @param ids 需要删除的纸张管理主键
     * @return 结果
     */

    public int deleteMesPaperByIds(Long[] ids) {
        return mesPaperMapper.deleteMesPaperByIds(ids);
    }

    /**
     * 删除纸张管理信息
     *
     * @param id 纸张管理主键
     * @return 结果
     */

    public int deleteMesPaperById(Long id) {
        return mesPaperMapper.deleteMesPaperById(id);
    }

    /**
     * 修改纸张信息状态
     *
     * @param mesPaper 纸张信息
     * @return 结果
     */

    public int updateMesPaperStatus(MesPaper mesPaper) {
        mesPaper.setUpdateBy(SecurityUtils.getUsername());
        mesPaper.setUpdateTime(DateUtils.getNowDate());
        return mesPaperMapper.updateMesPaper(mesPaper);
    }

    /**
     * 通过纸张信息名称查询纸张信息
     *
     * @param name 纸张信息名称
     * @return 纸张信息
     */

    public MesPaper selectMesPaperByName(String name) {
        return mesPaperMapper.selectMesPaperByName(name);
    }

    /**
     * 导入纸张信息数据
     *
     * @param mesPaperList    纸张信息数据
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */

    public String importPaper(List<MesPaper> mesPaperList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(mesPaperList) || mesPaperList.size() == 0) {
            throw new ServiceException("导入纸张信息数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (MesPaper paper : mesPaperList) {
            try {
                // 验证是否存在这个纸张
                MesPaper m = mesPaperMapper.selectMesPaperByName(paper.getName());
                if (StringUtils.isNull(m)) {
//                    if(org.apache.commons.lang3.StringUtils.isNotBlank(custom.getPhone())){
//                        String tel = "^1[3|4|5|6|7|8|9][0-9]\\d{8}$"; // 手机号正则校验
//                        if(!Pattern.matches(tel, custom.getPhone())){
//                            failureNum++;
//                            failureMsg.append("<br/>" + failureNum + "、联系电话 " + custom.getPhone() + " 有误");
//                        }
//                    }

                    paper.setCreateBy(operName);
                    mesPaperMapper.insertMesPaper(paper);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、纸张信息 " + paper.getName() + " 导入成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、纸张信息 " + paper.getName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、纸张信息 " + paper.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 修改纸张管理数量
     *
     * @param mesPaper 纸张管理
     * @return 结果
     */

    public int updateMesPaperQuantity(MesPaper mesPaper) {
        mesPaper.setUpdateBy(SecurityUtils.getUsername());
        mesPaper.setUpdateTime(DateUtils.getNowDate());
        int count = mesPaperMapper.updateMesPaperQuantity(mesPaper);
        return count;
    }


    public int updateProducePaperUseAmount(MesUseDetail useDetail) {
        int count = mesPaperMapper.updateProducePaperUseAmount(useDetail);
        return count;
    }


    //查询机台纸张

    public int selectMachinePaper(MesMachinePaper machinePaper) {
        int count = mesPaperMapper.selectMachinePaper(machinePaper);
        return count;
    }

    //新增机台纸张

    public int AddMachinePaper(MesMachinePaper machinePaper) {
        BigDecimal beforeNum = BigDecimal.ZERO;
        List<MesMachinePaper> listBefore = mesPaperMapper.selectMachinePaperMode(machinePaper);
        if (listBefore.size() > 0) {
            beforeNum = listBefore.get(0).getNumber();
        }
        int count = mesPaperMapper.AddMachinePaper(machinePaper);
        List<MesMachinePaper> list = mesPaperMapper.selectMachinePaperMode(machinePaper);
        if (list.size() > 0) {
            log.info("机台库存问题,机台变动前库存:" + beforeNum + ",机台变动后库存:" + list.get(0).getNumber() + ",机台ID:" + machinePaper.getMachineid() + ",纸张id:" + machinePaper.getPaperid() + ",变动数:" + machinePaper.getNumber() + ",加或减:" + machinePaper.getType());
        }
        return count;
    }

    //修改库存数

    public int updateMachinePaper(MesMachinePaper machinePaper) {
//        BigDecimal beforeNum = BigDecimal.ZERO;
//        List<MesMachinePaper> listBefore = mesPaperMapper.selectMachinePaperMode(machinePaper);
//        if (listBefore.size() > 0) {
//            beforeNum = listBefore.get(0).getNumber();
//        }
        int count = mesPaperMapper.updateMachinePaper(machinePaper);
//        List<MesMachinePaper> list = mesPaperMapper.selectMachinePaperMode(machinePaper);
//        if (list.size() > 0) {
//            log.info("机台库存问题,机台变动前库存:" + beforeNum + ",机台变动后库存:" + list.get(0).getNumber() + ",机台ID:" + machinePaper.getMachineid() + ",纸张id:" + machinePaper.getPaperid() + ",变动数:" + machinePaper.getNumber() + ",加或减:" + machinePaper.getType());
//        }
        return count;
    }


    public int cuttingMachinePaper(MesMachinePaper machinePaper) {
//        BigDecimal beforeNum = BigDecimal.ZERO;
//        List<MesMachinePaper> listBefore = mesPaperMapper.selectMachinePaperMode(machinePaper);
//        if (listBefore.size() > 0) {
//            beforeNum = listBefore.get(0).getNumber();
//        }
        int count = mesPaperMapper.cuttingMachinePaper(machinePaper);
//        List<MesMachinePaper> list = mesPaperMapper.selectMachinePaperMode(machinePaper);
//        if (list.size() > 0) {
//            log.info("机台库存问题,机台变动前库存:" + beforeNum + ",机台变动后库存:" + list.get(0).getNumber() + ",机台ID:" + machinePaper.getMachineid() + ",纸张id:" + machinePaper.getPaperid() + ",变动数:" + machinePaper.getNumber() + ",加或减:" + machinePaper.getType());
//        }
        return count;
    }


    public List<MesPaper> MachinePaperlist(MesPaper data) {
        List<MesPaper> list = mesPaperMapper.MachinePaperlist(data);
        return list;
    }


    public List<MesMachinePaper> selectMachinePaperByIds(MesMachinePaper data) {
        List<MesMachinePaper> list = mesPaperMapper.selectMachinePaperByIds(data);
        return list;
    }


    public List<MesMachinePaper> selectMachinePaperMode(MesMachinePaper data) {
        List<MesMachinePaper> list = mesPaperMapper.selectMachinePaperMode(data);
        return list;
    }



    public List<MesPaper> getPaperCirculationList(MesPaper mesPaper) {
        List<String> yearMonths = new ArrayList<>();
        if(StringUtils.isNotEmpty(mesPaper.getStartDate()) && StringUtils.isNotEmpty(mesPaper.getEndDate())) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate sDate = LocalDate.parse(mesPaper.getStartDate(), formatter);
            LocalDate eDate = LocalDate.parse(mesPaper.getEndDate(), formatter);
            LocalDate startDate = LocalDate.of(sDate.getYear(), sDate.getMonthValue(), sDate.getDayOfMonth());
            LocalDate endDate = LocalDate.of(eDate.getYear(), eDate.getMonthValue(), eDate.getDayOfMonth());
            LocalDate currentDate = startDate;
            while (!currentDate.isAfter(endDate)) {
                String yearMonth = String.format("%d-%02d", currentDate.getYear(), currentDate.getMonthValue());
                yearMonths.add(yearMonth);
                currentDate = currentDate.plus(1, ChronoUnit.MONTHS);
            }
        }
        if(yearMonths.size()>0){ //盘点日期
            String inventoryMonth=String.join(",",yearMonths);
            mesPaper.setInventoryMonth(inventoryMonth);
        }
        return mesPaperMapper.paperCirculationList(mesPaper);
    }

    // 纸张流转列表导出
    public AjaxResult exportPaperCirculationList(MesPaper mesPaper) {
        // 查询数据
        List<MesPaper> paperList = getPaperCirculationList(mesPaper);
        // 查询数据字典信息
        SysDictData sysDictData = new SysDictData();
        // 规格型号
        sysDictData.setDictType("mes_paper_specs");
        List<SysDictData> dataList1 = sysDictDataMapper.selectDictDataList(sysDictData);
        Map<String, String> specsMap = dataList1.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        // 品牌
        sysDictData.setDictType("mes_paper_brand");
        List<SysDictData> dataList = sysDictDataMapper.selectDictDataList(sysDictData);
        Map<String, String> brandMap = dataList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        /// 处理数据
        for (MesPaper paper : paperList) {
            // 平张/卷筒
            if(StringUtils.isNotEmpty(paper.getPackageType())){
                if("1".equals(paper.getPackageType())) paper.setPackageType("平张");
                else if("2".equals(paper.getPackageType())) paper.setPackageType("卷筒");
            }
            // 规格型号
            if(paper.getSpecs() != null){
                paper.setSpecsString(specsMap.get(paper.getSpecs().toString()));
            }
            // 品牌
            if(StringUtils.isNotEmpty(paper.getBrand())){
                paper.setBrand(brandMap.get(paper.getBrand()));
            }
            // 计量单位：1=公斤,2=吨,3=张,2=令
            if(StringUtils.isNotEmpty(paper.getUnit())){
                if("1".equals(paper.getUnit())) paper.setUnit("公斤");
                else if("2".equals(paper.getUnit())) paper.setUnit("吨");
                else if("3".equals(paper.getUnit())) paper.setUnit("张");
                else if("4".equals(paper.getUnit())) paper.setUnit("令");
            }
        }

        // 导出
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String filename = dateFormat.format(new Date()) + "_纸张流转列表.xls";
        String templateName = "纸张流转列表.xls";
        // 获取合计
        HashMap<String, Object> hashMap = new HashMap<>();
        try {
//            EasyExcelUtils.createExcel(response, templateName, filename, hashMap, paperList);
            return EasyExcelUtils.exportExcel(response, templateName, filename, hashMap, paperList);
        } catch (Exception e) {
            throw new BaseException("导出纸张流转列表失败：" + e.getMessage());
        }
    }
}
